package com.etlmaster.executor.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.etlmaster.jdbc.JdbcTemplate;



/**
 * @author Wugf
 * @date 2016-11-10
 */
public class DpExecutorDbLogUtils {
	private static String procLogTableName = DataCollectionUtils
			.getProperties("procLogTableName");

	private static String procStepLogTableName = DataCollectionUtils
			.getProperties("procStepLogTableName");

	private static Map<String,List<LogSqlEntry>> sqls = new HashMap<String,List<LogSqlEntry>>();

	private static Map<String,String> procStartTimes=new HashMap<String,String>();
	private static Map<String, String> stepStartTimeMap = new HashMap<String, String>();

	/*
	 * 记录整个程序开始日志
	 */
	public static void logProcStart(String sessionId,String procName, String taskId,String user) {
		String procStartTime = DataCollectionUtils.getCurrentTimestampByFormate();
		String del_old_sql = "delete from " + procLogTableName
				+ " WHERE PROC_NAME=? and CYCLE_ID=? ";
		String []objects={procName,taskId};
		List<LogSqlEntry> sqlList=setSqlList(sessionId);
		sqlList.add(new LogSqlEntry(del_old_sql,objects));
		String sql="insert into "
				+ procLogTableName
				+ " (PROC_NAME,CYCLE_ID,START_TIME,end_time, RESULT,REMARK,username) values(?,?,?,null,'-1','Running',?)";
		String []values={procName,taskId,procStartTime,user};
		sqlList.add(new LogSqlEntry(sql,values));
		procStartTimes.put(sessionId, procStartTime);
	}

	/*
	 * 记录整个程序结束日志
	 */
	public static void logProcEnd(String sessionId,String procName, String taskId,
			String result, String remark,String user) {
		String procStartTime=procStartTimes.get(sessionId);
		String del_old_sql = "delete from " + procLogTableName
				+ " WHERE PROC_NAME=? and CYCLE_ID=?  ";
		
		String []objects={procName,taskId};
		List<LogSqlEntry> sqlList=setSqlList(sessionId);
		sqlList.add(new LogSqlEntry(del_old_sql,objects));
		String sql = "insert into "
				+ procLogTableName
				+ " (PROC_NAME,CYCLE_ID,START_TIME,end_time, RESULT,REMARK,username) values(?,?,?,?,?,?,?)";
		String []values={procName,taskId,procStartTime,DataCollectionUtils.getCurrentTimestampByFormate() ,result,remark,user};
		sqlList.add(new LogSqlEntry(sql,values));
		batchUpdate(sessionId);
	}

	private  static void batchUpdate(String sessionId) {
		if (!DataCollectionUtils.getProperties("isLocalMode").equalsIgnoreCase(
				"y")) {
			try {/*
				getJdbcTemplate().batchUpdate(toArray());
				System.gc();
				*/
				
				for(LogSqlEntry entry:sqls.get(sessionId)){
					getJdbcTemplate().update(entry.getSql(), entry.getArgs());
				}
				
			} catch (Exception e) {
				LogWriter.addLog("ERROR", "更新执行日志失败，{}", e.getMessage());
			}
		}
		sqls.remove(sessionId);
	}
/*
	private static String[] toArray() {
		String[] sqlArray = new String[sqlList.size()];
		for (int i = 0; i < sqlList.size(); i++) {
			sqlArray[i] = sqlList.get(i);
		}
		return sqlArray;
	}
*/
	private static JdbcTemplate getJdbcTemplate() {
		try {
			return new JdbcTemplate();
		} catch (Exception e) {
			LogWriter.addLog("WARN", "数据源为空无法保存执行步骤日志到数据库");
			LogWriter.addLog("ERROR", "异常{}", e.getMessage());
		}
		return null;
	}

	public static void logStepStart(String sessionId,String stepId, String step_code,
			String procName, String taskId, String stepName) { // /登记开始运行的日志，如果已经存在日志，就更新，否则插入
		String del_old_sql = "delete from " + procStepLogTableName
				+ " where proc_name=? and cycle_id=? and step_seq=? ";
		String []objects={procName,taskId,stepId};
		List<LogSqlEntry> sqlList=setSqlList(sessionId);
		sqlList.add(new LogSqlEntry(del_old_sql,objects));
		
		stepStartTimeMap.put(procName + "_" + taskId + "_" + stepId,
				DataCollectionUtils.getCurrentTimestampByFormate());
	}

	public static void logStepEnd(String sessionId,String stepId, String step_code,
			String procName, String taskId, String stepName, String sql_text,
			int stepStateCode) { // /登记结束运行的日志

		String sql = "insert into "
				+ procStepLogTableName
				+ "(PROC_NAME,CYCLE_ID,STEP_SEQ,STEP_NAME,START_TIME,end_time,STEP_RESULT,SQL_TEXT,step_code) values(?,?,?,?,?,?,?,?,?)";
		String []values={procName,taskId,stepId,stepName,stepStartTimeMap.get(procName + "_" + taskId + "_" + stepId),DataCollectionUtils.getCurrentTimestampByFormate(),
				stepStateCode+"",sql_text,step_code};
		List<LogSqlEntry> sqlList=setSqlList(sessionId);
		sqlList.add(new LogSqlEntry(sql,values));		
		checkListSize(sessionId);
	}

	private static void checkListSize(String sessionId) {
		int commit_size = DataCollectionUtils.getProperties("commit_size") != null ? Integer
				.parseInt(DataCollectionUtils.getProperties("commit_size"))
				: 1000;
		if (sqls.get(sessionId).size() > commit_size) {
			batchUpdate(sessionId);
		}
	}
	private static List<LogSqlEntry> setSqlList(String sessionId){
		List<LogSqlEntry> sqlList=null;
		if(sqls.get(sessionId)==null)
		{
			sqlList=new ArrayList<LogSqlEntry>();
			sqls.put(sessionId, sqlList);
		}
		else
			sqlList=sqls.get(sessionId);
		return sqlList;
	}

}
